﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Zhuang.Utility.WinForm.Forms;
using System.Collections;
using Zhuang.Utility.Common.DataBase;
using Zhuang.DAL.Access;
using Zhuang.Model.Access;
using Zhuang.WinForm.ControlLibrary.Components.Forms;

namespace Zhuang.WinForm.Sales
{
    public partial class Pos : Form
    {

        Pos_CurrentOrderDAL pos_CurrentOrderDAL = new Pos_CurrentOrderDAL(); 

        public Pos()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            MessageBox.Show("search");
        }

        private void tbCondition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SelectProduct();
            }

            ShortcutKeyDown(sender,e);
        }

        private void SelectProduct() 
        {
            string strCondition = tbCondition.Text.Trim();

            string strSql = string.Format("select * from Product where 1=1 and BarCode Like '%{0}%' or ProductName like '%{0}%' or ProductCode like '%{0}%' or SearchCode like '%{0}%'", strCondition, strCondition);

            //DataTable dt = SqlHelper.Query(strSql).Tables[0] ;

            SearchSelect ss = new SearchSelect(strSql);

            ss.QueryDBEvent += QueryDB;

            SearchSelect.Setting settings = new SearchSelect.Setting();

            ArrayList alFitlerFies = new ArrayList();
            alFitlerFies.Add("BarCode");
            alFitlerFies.Add("ProductName");
            alFitlerFies.Add("ProductCode");
            settings.AlFitlerFiels = alFitlerFies;


            ArrayList alVisibleFields = new ArrayList();
            alVisibleFields.Add("ProductName");
            alVisibleFields.Add("BarCode");
            alVisibleFields.Add("ProductCode");
            alVisibleFields.Add("SearchCode");
            alVisibleFields.Add("Unit");
            alVisibleFields.Add("Description");
            alVisibleFields.Add("RetailPrice");
            settings.AlVisibleFields = alVisibleFields;

            Dictionary<string, string> dicHeadText = new Dictionary<string, string>();

            dicHeadText.Add("ProductName", "商品名称");
            dicHeadText.Add("BarCode", "商品条码");
            dicHeadText.Add("ProductCode", "商品编号");
            dicHeadText.Add("SearchCode", "助记码");
            dicHeadText.Add("Unit", "单位");
            dicHeadText.Add("Description", "描述");
            dicHeadText.Add("RetailPrice", "零售价");

            settings.DicFieldsHeadText = dicHeadText;

            settings.IsDefaultUnvisibleColumns = true;
            settings.IsSingle = true;

            ss.Settings = settings;

            ss.ShowDialog();

            DataTable dtResult = ss.GetResult();

            if (dtResult.Rows.Count > 0)
            {

                tbCondition.Text = "";
                AddProduct(Convert.ToInt32(dtResult.Rows[0]["ProductId"].ToString()));

            }
        }

        private void AddProduct(int productId)
        {
            pos_CurrentOrderDAL.Add(productId);
            LoadMainData();
        }

        private void LoadMainData()
        {

            int count = dgvMain.Rows.Count;


            int selectedIndex = 0;
            if (dgvMain.SelectedRows.Count > 0)
            {
                selectedIndex= dgvMain.SelectedRows[0].Index;
            }

            dgvMain.DataSource = pos_CurrentOrderDAL.Get();
            CalculateSum();

            if (dgvMain.Rows.Count > 0)
            {
                if (count > dgvMain.Rows.Count)
                {
                    selectedIndex = selectedIndex - 1;
                }

                if (selectedIndex < dgvMain.Rows.Count)
                {
                    dgvMain.Rows[selectedIndex].Selected = true;
                    dgvMain.CurrentCell = dgvMain.Rows[selectedIndex].Cells["ProductName"];
                }
            }

            
        }

        private DataTable QueryDB(string strSql)
        {
            return OleDbHelper.Query(strSql).Tables[0];
        }

        private void tbCondition_DoubleClick(object sender, EventArgs e)
        {
            SelectProduct();
        }

        private void Pos_Load(object sender, EventArgs e)
        {
            dgvMain.AutoGenerateColumns = false;
            LoadMainData();
        }

        private void Pos_Shown(object sender, EventArgs e)
        {
            
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            DeleteCurrentRow();
        }


        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            DeleteAllRow();
        }

        private void dgvMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteCurrentRow();
            }else if (e.KeyCode == Keys.Subtract)
            {

                int productId = Convert.ToInt32(dgvMain.SelectedRows[0].Cells["ProductId"].Value);

                pos_CurrentOrderDAL.SubtractProductQuantity(productId);

                LoadMainData();

            }
            else if (e.KeyCode == Keys.Add)
            {
                int productId = Convert.ToInt32(dgvMain.SelectedRows[0].Cells["ProductId"].Value);

                pos_CurrentOrderDAL.AddProductQuantity(productId);
                LoadMainData();
            }

            ShortcutKeyDown(sender,e);
        }


        private void DeleteAllRow()
        {
            pos_CurrentOrderDAL.Delete();
            LoadMainData();
        }

        private void DeleteCurrentRow()
        {
            if (dgvMain.SelectedRows.Count > 0)
            {
                int id = Convert.ToInt32(dgvMain.SelectedRows[0].Cells["CurrentOrderId"].Value);
                pos_CurrentOrderDAL.Delete(id);
                LoadMainData();
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            PendingOrder();

        }

        private void PendingOrder()
        {
            PendingOrder po = new PendingOrder();
            po.StartPosition = FormStartPosition.CenterParent;
            po.ShowDialog();
            if (po.DialogResult == DialogResult.OK)
            {
                DeleteAllRow();
            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {

            if (dgvMain.Rows.Count > 0)
            {
                DialogResult dr= MessageBox.Show("当前有未结帐商品，是否先进行挂单？","",MessageBoxButtons.YesNoCancel);

                if (dr == DialogResult.Yes)
                {
                    PendingOrder();
                }
                else if (dr == DialogResult.No) { }
                else
                {
                    return;
                }

            }

            string strSql = "";

            //DataTable dt = SqlHelper.Query(strSql).Tables[0] ;

            SearchSelect ss = new SearchSelect();

            //ss.QueryDBEvent += QueryDB;

            SearchSelect.Setting settings = new SearchSelect.Setting();


            ArrayList alUnvisibleFields = new ArrayList();
            alUnvisibleFields.Add("PendingOrderMasterId");
            alUnvisibleFields.Add("ProductId");

            settings.AlUnvisibleFields = alUnvisibleFields;

            ArrayList alFitlerFies = new ArrayList();
            alFitlerFies.Add("PendingOrderName");
            settings.AlFitlerFiels = alFitlerFies;

            Dictionary<string, int> dicFieldsWidth = new Dictionary<string, int>();
            dicFieldsWidth.Add("PendingOrderName", 200);
            dicFieldsWidth.Add("PendingOrderDate",150);

            settings.DicFieldsWidth = dicFieldsWidth;
           
            Dictionary<string, string> dicHeadText = new Dictionary<string, string>();

            dicHeadText.Add("PendingOrderName", "挂单名");
            dicHeadText.Add("PendingOrderDate", "挂单日期");
           
            settings.DicFieldsHeadText = dicHeadText;

            //settings.IsDefaultUnvisibleColumns = true

            strSql = "select * from Pos_PendingOrderMaster";
            ss.Dt = OleDbHelper.Query(strSql).Tables[0];
            strSql = "select PendingOrderMasterId,ProductName as 商品名称,UnitPrice as 单价,Quantity as 数量 from Pos_PendingOrderDetail";
            ss.DtMx = OleDbHelper.Query(strSql).Tables[0];
            settings.HasMx = true;
            settings.IsShowMx = true;
            settings.IsSingle = true;
            settings.IdName = "PendingOrderMasterId";

            ss.Settings = settings;

            ss.ShowDialog();

            DataTable dtResult = ss.GetResult();


            if (dtResult.Rows.Count > 0)
            {
                int id =Convert.ToInt32(dtResult.Rows[0]["PendingOrderMasterId"].ToString());

                pos_CurrentOrderDAL.AddByPendingOrder(id);
                LoadMainData();
            }
            
        }


        private void CalculateSum()
        {
            if (dgvMain.Rows.Count > 0)
            {
                decimal totalQuantity = 0;
                decimal totalAmount = 0;

                foreach (DataGridViewRow dgvr in dgvMain.Rows)
                {
                    totalQuantity = totalQuantity + Convert.ToDecimal(dgvr.Cells["Quantity"].Value);
                    totalAmount = totalAmount + Convert.ToDecimal(dgvr.Cells["Quantity"].Value) * Convert.ToDecimal(dgvr.Cells["UnitPrice"].Value);

                }
                lbTotalQuantity.Text = totalQuantity.ToString("N2");
                lbTotalAmount.Text = totalAmount.ToString("N2");

            }
            else
            {
                lbTotalQuantity.Text = "0.00";
                lbTotalAmount.Text = "0.00";
            }
        }

        private void Pos_KeyDown(object sender, KeyEventArgs e)
        {
            ShortcutKeyDown(sender,e);

        }

        private void ShortcutKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.End)
            {
                ShowPay();
            }
        }

        private void btnPay_Click(object sender, EventArgs e)
        {
            if (dgvMain.Rows.Count > 0)
            {
                ShowPay();
                
            }

        }

        private  void ShowPay()
        {

            PayEntity payEntity = new PayEntity();
            payEntity.Payable = lbTotalAmount.Text.Trim();

            Pay p = new Pay(payEntity);
            p.StartPosition = FormStartPosition.CenterParent;
            DialogResult dr = p.ShowDialog();

            if (dr == DialogResult.OK)
            {
                LoadMainData();
            }

        }

        private void btnPay_KeyDown(object sender, KeyEventArgs e)
        {
            ShortcutKeyDown(sender,e);
        }

        
    }
}
